package com.workflow.engine.eb.steps.jd.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.workflow.engine.core.flow.IStep;
import com.workflow.engine.core.flow.StepState;
import com.workflow.engine.parser.utils.RequestUtil;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import static com.workflow.engine.parser.utils.StepStateUtil.successfulStepState;

/**
 * Created by Administrator on 2017/6/7.
 */
public class JDGetLoginParams implements IStep {

    private static final Logger logger = LoggerFactory.getLogger(JDGetLoginParams.class);

    @Override
    public StepState run(Map<String, Object> context) throws Exception {
        String token = (String)context.get("password");
        String params = getLoginParams(token);
        logger.info("从浏览器反馈回来的页面信息：{}", params);
        JSONObject jsonObject = JSON.parseObject(params);
        context.put("uuid", jsonObject.get("uuid"));
        context.put("_t", jsonObject.get("_t"));
        context.put("eid", jsonObject.get("eid"));
        context.put("fp", jsonObject.get("fp"));
        context.put("loginType", jsonObject.get("loginType"));
        context.put("loginname", context.get("username"));
        context.put("nloginpwd", jsonObject.get("nloginpwd"));
        context.put("chkRememberMe", jsonObject.get("chkRememberMe"));
        context.put("authcode", jsonObject.get("authcode"));
        context.put("pubKey", jsonObject.get("pubKey"));
        context.put("sa_token", jsonObject.get("sa_token"));
        context.put("authCodeUrl", jsonObject.get("authCodeUrl"));
        context.put("seqSid", jsonObject.get("seqSid"));

        BasicCookieStore cookieStore = RequestUtil.getCookieStore();
        JSONArray cookieArray = (JSONArray) jsonObject.get("cookies");
        for (Object ele: cookieArray) {
            JSONObject json = (JSONObject) ele;
            final String name = (String) json.get("name");
            final String value = (String) json.get("value");
            final String path = json.get("path") != null ? (String)json.get("path") : null;
//            final Integer expiry = json.get("expiry") != null ? (Integer) json.get("expiry") : 0;
            final String expires = json.get("expires") != null ? (String) json.get("expires") : null;
            final String domain =  json.get("domain") != null ? (String) json.get("domain") : null;
            final Boolean secure = json.get("secure") != null ?  (Boolean)json.get("secure") : false;
            BasicClientCookie cookie = new BasicClientCookie(name, value);
            cookie.setPath(path);
            if(expires != null){
                cookie.setExpiryDate(parserDate(expires));
            }
            cookie.setDomain(domain);
            cookie.setSecure(secure);
            cookieStore.addCookie(cookie);
        }
        context.put("localStorage", jsonObject.get("localStorage"));
        return successfulStepState(this);
    }

    public static String getLoginParams(String pwd) throws IOException {
        Runtime rt = Runtime.getRuntime();
        //phantomjs 和codes.js的路径之间有个空格 本代码只是测试用的绝对路径
        Process p = rt.exec("phantomjs C:\\dev\\phantomjs-2.1.1-windows\\examples\\jd.js https://passport.jd.com/new/login.aspx " + pwd + " --proxy=127.0.0.1:8888 --proxy-type=http --ignore-ssl-errors --ssl-protocol=tlsv1.2");
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sbf = new StringBuffer();
        String tmp = "";
        while((tmp = br.readLine())!=null){
            sbf.append(tmp);
        }
        return sbf.toString();
    }

    public static Date parserDate(String stringDate) throws ParseException {
        final String[] WEEKDAYS = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        final String[] MONTHS = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
        DateFormatSymbols sym = new DateFormatSymbols(Locale.CHINA);
        sym.setShortWeekdays(WEEKDAYS);
        sym.setWeekdays(WEEKDAYS);
        sym.setMonths(MONTHS);
        SimpleDateFormat f = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", sym);
        return f.parse(stringDate);
    }

}
